<style>
.em {
  position: relative;

  .tip {
    position: absolute;
    top: -10px;
    right: -10px;
    background-color: red;
    color: white;
    border-radius: 50%;
    width: 15px;
    height: 15px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 10px;
  }
}

.post_main {

  min-height: 100vh;
  margin: 0 300px;
  width: 100vw - 600px;
  padding: 10px;
  background: #ffffff;
  border: #dedede solid 1px;
  z-index: 0;
}

.article {
  padding: 100px;
}

img {
  max-width: 100%;
}

.back {
  position: fixed;
  top: 0;
  left: 0;
  height: 100vh;
  width: 100vw;
  background: rgba(31, 31, 31, 0.5);
  z-index: 0;
}

.slect {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 370px;
  padding: 20px 30px;
  border-radius: 10px;
  background: rgba(255, 255, 255, 1);
  display: flex;
  z-index: 1;

  .option {
    width: 45%;
    margin: 10px;
    font-size: 36px;
    border: rgb(51, 118, 205) 1px solid;
    border-radius: 5px;
    display: flex;
    justify-content: center;
    align-items: center;
    writing-mode: vertical-rl;
    text-orientation: upright;
  }
}

.correctArticle {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 370px;
  padding: 20px 30px;
  border-radius: 10px;
  background: rgba(87, 154, 209, 0.8);
  z-index: 1;
}

.correctTextList {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 800px;
  height: 80vh;
  padding: 20px 30px;
  border-radius: 10px;
  background: rgb(255, 255, 255);
  z-index: 1;

  .infinite-list {
    height: calc(80vh - 80px);
    border: #aaa 1px solid;
  }

}

.background {
  position: absolute;
  top: 0;
  right: 0;
  height: 40px;
  width: 40px;
  border-radius: 5px;

  .close {
    position: absolute;
    top: 0;
    right: 0;
    height: 30px;
    width: 30px;
    margin: 5px;
    background-image: url("../assets/image/close.png");
    background-size: cover;
  }
}

.background:hover {
  background-color: rgb(213, 50, 48);
}

.correctTextItem {
  display: flex;
  flex-direction: column;
  padding: 5px;

  .correctUser {
    display: flex;
    height: 20px;
    width: 100%;
    align-items: center;
    padding: 10px 0;

    .avatar {
      height: 20px;
      width: 20px;

      img {
        height: 20px;
        width: 20px;
      }
    }

    .nickName {
      margin-left: 10px;
      font-size: 18px;
      color: #aaa;
    }
  }

  .correctText {}

  .correctTextOption {
    display: flex;
    justify-content: space-evenly;

    img {
      height: 20px;
      width: 20px;
    }

    padding-bottom: 5px;
    border-bottom: #aaa 1px solid;
  }
}

.label {
  font-size: 18px;
}

.correctUIOption {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.pd_title {
  position: relative;
  border-bottom: black 1px solid;
  height: 30px;
  width: 50vw;
  margin: 20px 0 10px 0;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 0;

  .pd_title_input {
    width: 50vw;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
  }
}

.post_detail_left {
  position: absolute;
  width: 300px;

  .author_info {
    width: 100%;

  }
}

.post_detail_right {
  position: absolute;
  width: calc(300px - 20px);
  top: 50px;
  right: 0;
  margin: 10px;
}

.article_recommend,
.related_products {
  background: #ffffff;
}

.article_recommend h2 {
  text-align: center;
  margin-bottom: 10px;
}

.article_grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}

.article_item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.article_cover {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 5px;
}

.article_title {
  font-size: 14px;
  color: #333;
}

.post_detail_right>.article_recommend,
.post_detail_right>.related_products {
  margin-bottom: 25px;
  /* 添加模块之间的间距 */
}

.related_products h2 {
  text-align: center;
  margin-bottom: 10px;
}

.product_grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  /* 2 列 */
  gap: 10px;
  /* 网格项之间的间距 */
}

.product_item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

}

.jump_link {
  text-decoration: none;
  /* 去除链接的默认下划线 */
  color: inherit;
  /* 继承父元素的字体颜色 */
}

.product_image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  margin-bottom: 5px;
}

.product_name {
  font-size: 14px;
  color: #333;
  margin: 5px 0;
  flex-grow: 1;
}

.product_info {
  display: flex;
  justify-content: space-around;
  width: 100%;
  font-size: 14px;
}

.product_sales {
  color: #888;
}

.product_price {
  font-size: 14px;
  color: red;
}

.pd_interaction {
  display: flex;
  justify-content: space-around;
  margin: 10px 300px;

  .pd_interaction_col {
    img {
      height: 50px;
      width: 50px;
    }
  }
}

.custom-btn {
  position: fixed;
  left: 50px;
  bottom: 50px;
  background-color: #4caf50;
  /* 按钮背景色 */
  color: white;
  /* 按钮文字颜色 */
  border: none;
  /* 去掉边框 */
  border-radius: 8px;
  /* 圆角 */
  padding: 10px 20px;
  /* 内边距 */
  font-size: 16px;
  /* 字体大小 */
  cursor: pointer;
  /* 鼠标指针变为手型 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);
  /* 添加阴影 */
  transition: all 0.3s ease;
  /* 增加过渡效果 */
}

.custom-btn:hover {
  background-color: #45a049;
  /* 鼠标悬浮时颜色变化 */
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.3);
  /* 鼠标悬浮时阴影增强 */
}

.custom-btn:active {
  background-color: #3e8e41;
  /* 按下时颜色 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  /* 按下时阴影减弱 */
  transform: translateY(2px);
  /* 模拟按下效果 */
}
</style>
<template>
  <div style="background: linear-gradient(to bottom, #e8f5e9, #ffffff);">
    <HomeTop style="position: sticky;top: 0;z-index: 10;" />
    <div class="post_detail_left">
      <div class="author_info">
        <authorInfo :userInfo="userInfo"></authorInfo>
      </div>
    </div>
    <div class="post_main">
      <div class="pd_title">
        <div class="pd_title_input">{{ postDetail.title }}</div>
      </div>
      <div class="article">
        <div v-html="postDetail.content"></div>
      </div>
      <div class="back" v-if="isShowCorrectUI == true">
        <div class="slect" v-if="UIType == 0">
          <div class="option" @click="UIType = 1">我要补充</div>
          <div class="option" @click="UIType = 2; getCorrectList(1);">查看他人补充</div>
          <div class="background" @click="closeCorrectUI">
            <div class="close">
            </div>
          </div>
        </div>
        <div class="correctArticle" v-if="UIType == 1">
          <div class="label">原内容：</div>
          <el-input type="textarea" disabled :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入内容"
            v-model="originalText">
          </el-input>
          <div class="label">补充内容：</div>
          <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 5 }" placeholder="请输入内容" v-model="correctText">
          </el-input>
          <div class="correctUIOption">
            <el-button type="danger" plain @click="closeCorrectUI">取消</el-button>
            <el-button type="primary" plain @click="saveCorrect(selectTextId)">确定</el-button>
          </div>
        </div>
        <div class="correctTextList" v-if="UIType == 2">
          原内容：{{ originalText }}
          <br />
          补充内容：
          <ul class="infinite-list" v-infinite-scroll="load" style="overflow:auto;">
            <li v-for="(item, index) in correctList" class="infinite-list-item">
              <div class="correctTextItem">
                <div class="correctUser">
                  <div class="avatar">
                    <img :src="item.avatar" alt="头像">
                  </div>
                  <div class="nickName">{{ item.nickname }}</div>
                </div>
                <div class="correctText">{{ item.correctText }}</div>
                <div class="correctTextOption">
                  <img src="../assets/image/like.png" alt="点赞" v-if="isLikeList[index].isLike == false"
                    @click="toggleLike(index, true)">
                  <img src="../assets/image/liked.png" alt="已点赞" v-if="isLikeList[index].isLike == true"
                    @click="toggleLike(index, false)">>
                  <!-- <img src="../assets/image/tip-off.png" alt="举报"> -->
                </div>
              </div>
            </li>
            <div class="background" @click="closeCorrectUI">
              <div class="close">
              </div>
            </div>
          </ul>
        </div>
      </div>
    </div>
    <div class="post_detail_right">
      <!-- 推荐文章模块 -->
      <div class="article_recommend">
        <!-- 推荐文章标题 -->
        <h2>相关推荐</h2>
        <!-- 文章选项区域 -->
        <div class="article_grid">
          <!-- 使用 v-for 动态渲染文章项 -->
          <div class="article_item" v-for="(article, index) in recommend_articles" :key="index">
            <a :href="'PostDetail?id=' + article.id" class="jump_link">
              <img :src="article.cover" :alt="article.title" class="article_cover">
              <p class="article_title">{{ article.title }}</p>
            </a>
          </div>
        </div>
      </div>
      <!-- 相关商品推荐模块 -->
      <div class="related_products">
        <h2>相关商品推荐</h2>
        <div class="product_grid">
          <div class="product_item" v-for="(product, index) in products" :key="index">
            <a :href="product.detail_url" class="jump_link">
              <img :src="product.pic_path" :alt="product.title" class="product_image">
              <p class="product_name">{{ product.title }}</p>
              <div class="product_info">
                <p class="product_price">{{ product.sale_price }}￥</p>
                <p class="product_sales">{{ product.real_sales }}</p>
              </div>
            </a>
          </div>
        </div>

      </div>
    </div>
    <div class="pd_interaction">
      <div class="pd_interaction_col">
        <img src="../assets/image/liked.png" alt="" v-if="isLike == 1" @click="like(0)">
        <img src="../assets/image/like.png" alt="" v-else @click="like(1)">
      </div>
      <div class="pd_interaction_col">
        <img src="../assets/image/collected.png" alt="" v-if="isCollect == 1" @click="collect(0)">
        <img src="../assets/image/collect.png" alt="" v-else @click="collect(1)">
      </div>
    </div>
    <div class="pd_interaction">
      <button class="custom-btn" @click="newPageNeedToken(`/ClassTest?id=${postId}`)">测试学习成果</button>
    </div>
  </div>
</template>

<script>
import VueMarkdown from 'vue-markdown'
import request from '@/utils/request';
import MarkdownIt from 'markdown-it';
import HomeTop from '../components/HomeTop.vue'
import authorInfo from '@/components/authorInfo.vue'
import { newPage, newPageNeedToken } from '@/utils/commonFunction'
export default {
  components: {
    VueMarkdown,
    HomeTop,
    authorInfo
  },
  data() {
    return {
      isLike: null,
      isCollect: null,
      UIType: 0,
      postDetail: null,
      htmlString: null,
      correctNum: [
      ],
      correctList: [],
      postId: 5,
      eachText: [],
      originalText: '',
      correctText: '',
      isShowCorrectUI: false,
      selectTextId: null,
      userInfo: null,
      recommend_articles: [
      ],
      products: [
      ],
      isLikeList: [

      ]
    }
  },
  async created() {

    this.postId = this.$route.query.id;
    await this.getCorrectNum();
    await this.getData(this.postId);
    this.getInteraction();
    this.addViews();
    await this.getRecommendArticlesData();
    await this.getRecommendProductsData();
    this.addWatchRemember();
  },
  updated() {
    this.addClickEvent();
  },
  methods: {
    newPage,
    newPageNeedToken,
    addViews() {
      request.post(`posts/${this.postId}`).then(res => {
      });
    },
    getInteraction() {
      request.get(`/user_collects/${this.postId}`).then(res => {
        if (res.code === 200) {
          this.isCollect = res.data;
        }
      });

      request.get(`/user_likes/${this.postId}`).then(res => {
        if (res.code == 200) {
          this.isLike = res.data;
        }
      })
    },
    like(flag) {
      request.post("/user_likes", {
        likedId: this.postId,
        isLike: flag
      }).then(res => {
        if (res.code == 200) {
          this.isLike = !this.isLike;
        }
      })
    },
    collect(flag) {
      request.post("/user_collects", {
        collectedId: this.postId,
        isCollect: flag
      }).then(res => {
        if (res.code == 200) {
          this.isCollect = !this.isCollect;
        }
      })
    },
    load() {

    },
    closeCorrectUI() {
      this.isShowCorrectUI = false;
    },
    saveCorrect(textId) {
      var userId = JSON.parse(localStorage.getItem('userInfo')).id;
      request.post(`blog_corrects`, {
        postId: this.postId,
        textId: textId,
        correctText: this.correctText,
        authorId: userId,
        likeCount: 0,
      }).then(res => {
        this.isShowCorrectUI = false;
        this.$message({
          message: '发布成功,刷新查看最新效果',
          type: 'success'
        });
      }).catch(err => {
        console.error('Error fetching post:', err);
      });
    },
    getData() {
      // 发起请求获取帖子内容
      return request.get(`posts/${this.postId}`).then(res => {
        this.postDetail = res;
        this.getUserInfo(this.postDetail.authorId);
      }).catch(err => {
        console.error('Error fetching post:', err);
      });
    },
    getRecommendArticlesData() {
      request.post('/recommend/articles', this.postDetail).then(res => {
        this.recommend_articles = res.data;
      })
    },
    getRecommendProductsData() {
      request.post('/recommend/product', this.postDetail).then(res => {
        this.products = res.data;
      })
    },
    getUserInfo(authorId) {
      request.get(`/sys_users/${authorId}`)
        .then(res => {
          this.userInfo = res.data;
        })
    },
    getCorrectList(pageNum) {
      request.get(`blog_corrects`, {
        params: {
          pageNum: pageNum,
          pageSize: 10,
          postId: this.postId,
          textId: this.selectTextId,
        }
      }
      ).then(res => {
        this.correctList = res
        this.correctList.forEach(item => {
          this.isLikeList.push({
            isLike: false
          })
        })
      }).catch(err => {
        console.error('Error fetching post:', err);
      });
    },
    getCorrectNum() {
      request.get(`correct_num`, {
        params: {
          postId: this.postId,
        }
      }
      ).then(res => {
        this.correctNum = res
      }).catch(err => {
        console.error('Error fetching post:', err);
      });
    },
    addWatchRemember() {
      let jsonString = localStorage.getItem('userInfo');
      let userId = JSON.parse(jsonString).id;
      let postId = this.postDetail.id;
      let tags = this.postDetail.tags;
      // 检查参数是否为空
      if (!userId || !postId || !tags) {
        return;
      }

      // 发送 POST 请求来记录浏览
      request.post(`/userWatchRemember/add`, {
        userId: userId,
        postId: postId,
        tags: tags || ''
      }).then(res => {
        // 检查请求是否成功
        if (res.code === 200) {
          console.log('View added successfully');
        } else {
          console.log('Failed to add view: ', res.msg);
        }
      }).catch(err => {
        console.log('Error adding view: ', err);
      });
    },

    addClickEvent() {
      var elements = document.querySelectorAll('.em');
      elements.forEach((element) => {
        var element_id = element.id;
        //获取数组correctNum中的key为element_id的值
        for (var i = 0; i < this.correctNum.length; i++) {
          if (this.correctNum[i][element_id] !== undefined) {
            var value = this.correctNum[i][element_id];
            if (value != 0) {
              element.style.background = '#527f37';
              if (value < 10) {
                element.style.fontSize = (16 + value) + 'px';
              } else {
                element.style.fontSize = (16 + 10) + 'px';
              }

              // 创建红圈元素
              var tip = document.createElement('span');
              tip.classList.add('tip');
              tip.textContent = value; // 在红圈里显示 value 的值

              // 将红圈添加到元素的右上角
              element.appendChild(tip);
            }
            break;
          }
        }

        element.addEventListener('click', (event) => {
          // 获取这个元素的id
          var id = event.target.id;
          this.selectTextId = id;
          this.isShowCorrectUI = true;
          this.UIType = 0
          this.originalText = event.target.innerHTML;
          this.originalText = this.originalText.replace(/<span class="tip">.*?<\/span>/g, '');
        });
      });
    },
    toggleLike(index, flag) {
      // 切换 isLike 的状态
      this.isLikeList[index].isLike = flag;
    }
  },

}
</script>
